package com.test.sdk.core.exception;

import com.test.sdk.common.pojo.LocalPrompt;
import com.test.sdk.common.util.*;
import com.test.sdk.core.cache.LocalPromptCache;
import com.test.sdk.core.cache.PromotionChannelCache;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 徒有琴
 */
@Component
public class SdkExceptionHandler implements HandlerExceptionResolver {
    @Nullable
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
        handlerException(httpServletRequest,httpServletResponse,e);
        return null;
    }

    public static void handlerException(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Exception e){

        if (e instanceof SdkException) {
            Integer prtChid = RequestUtil.getInteger(httpServletRequest, "prtchid");
            Integer language= PromotionChannelCache.getLanguageType(prtChid);
            LocalPrompt prompt= LocalPromptCache.getPromot(e.getMessage(),language);
            ResponseTO res=new ResponseTO();
            ErrorCodeTO code=null;
            if(prompt==null){
                code= ErrorConstants.SYSTEM_UNKNOWN;
            }else{
                code= new ErrorCodeTO(prompt.getCode(),prompt.getValue());
            }
            res.setError(code);
            String json = JsonUtil.getJSON(res);
            httpServletResponse.setContentType("application/json; charset=UTF-8");
            try {
                httpServletResponse.getWriter().write(json);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
